package com.powernode.config;

import cn.hutool.core.util.ObjectUtil;
import com.powernode.constant.AuthConstants;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @Description: feign token传递
 * @Author: Tong Ziyu
 * @Date: 2024/11/6 22:15
 */
@Component
public class FeignInterceptor implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate requestTemplate) {
        // 获取当前请求的上下文
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

        if (ObjectUtil.isNotNull(requestAttributes)) {
            HttpServletRequest request = requestAttributes.getRequest();

            if (ObjectUtil.isNotNull(request)) {

                String token = request.getHeader(AuthConstants.AUTHORIZATION);

                if (StringUtils.hasText(token)) {

                    // 将token放到请求头中
                    requestTemplate.header(AuthConstants.AUTHORIZATION, token);
                    return;
                }
            }
        }

        // 如果是定时器(没有token) 定时来调用该模块方法,则给一个指定的token
        // 已经在redis中设置了一个永久不会过期的token:edda194b-87c5-49be-8319-3d0795026b6f
        requestTemplate.header(AuthConstants.AUTHORIZATION,AuthConstants.BEARER+ "edda194b-87c5-49be-8319-3d0795026b6f");

    }
}
